//
//  ShowBigViewController.m
//  Investment
//
//  Created by xujiuming on 14-12-7.
//  Copyright (c) 2014年 xujiuming. All rights reserved.
//

#import "ShowBigViewController.h"
#import "MBProgressHUD.h"
#import "Util.h"

#define IOS7LATER  [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0
@interface ShowBigViewController ()<MBProgressHUDDelegate>
{
    //MKNetworkEngine* _engine;
    MBProgressHUD *HUD;
}
@property (nonatomic, retain) NSString *imagepath;
@end

@implementation ShowBigViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置导航栏的rightButton
    /*
    rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightbtn.frame=CGRectMake(0, 0, 22, 22);
    [rightbtn setImage:[UIImage imageNamed:@"OK.png"] forState:UIControlStateNormal];
    [rightbtn addTarget:self action:@selector(OK:)forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightbtn];
    */
    
    self.navigationItem.rightBarButtonItem =
    [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"完成", nil)
                                     style:UIBarButtonItemStylePlain
                                    target:self
                                    action:@selector(complete:)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
     //设置导航栏的leftButton
    UIButton *leftbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftbtn.frame=CGRectMake(0, 0, 11, 20);
    
    [leftbtn setImage:[UIImage imageNamed:@"fanhui.png"] forState:UIControlStateNormal];
    [leftbtn addTarget:self action:@selector(dismiss)forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftbtn];
    if([[[UIDevice currentDevice]systemVersion] doubleValue]>=7.0){
        self.navigationController.navigationBar.barTintColor = [self colorWithHex:0x18b4ed alpha:1.0f];
        [[UINavigationBar appearance]setTintColor:[UIColor whiteColor]];
    }else{
        self.navigationController.navigationBar.tintColor = [self colorWithHex:0x18b4ed alpha:1.0f];
    }
    [self layOut];
    
    //self.imagepath=[NSString stringWithFormat:@"%@/sendImage.jpg",sandBox];//发送图片的路径
}
-(UIColor*) colorWithHex:(NSInteger)hexValue alpha:(CGFloat)alphaValue
{
    return [UIColor colorWithRed:((float)((hexValue & 0xFF0000) >> 16))/255.0
                           green:((float)((hexValue & 0xFF00) >> 8))/255.0
                            blue:((float)(hexValue & 0xFF))/255.0 alpha:alphaValue];
}
-(void)layOut{
    self.view.backgroundColor = [UIColor blackColor];
            //arrayOK里存放选中的图片
   
    //CGFloat YHeight=([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)?(64.0f):(44.0f);
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    if (IOS7LATER)
    {
        _scrollerview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; // - 50)];
         //_btnOK = [[UIButton alloc]initWithFrame:CGRectMake(244,  _scrollerview.frame.size.height + 9, 61, 32)];
    }
#endif
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
    }
    else
    {
        _scrollerview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; //- 100)];
        // _btnOK = [[UIButton alloc]initWithFrame:CGRectMake(244,  _scrollerview.frame.size.height + 11, 61, 32)];
    }
    
    
    //显示选中的图片的大图
  
    _scrollerview.backgroundColor = [UIColor whiteColor];
    _scrollerview.delegate = self;
    //NSLog(@"self.arrayOK.count is %d",self.arrayOK.count);
 
    for (int i=0; i<[self.arrayOK count]; i++) {
       ALAsset *asset=self.arrayOK[i];
        
        UIImageView *imgview=[[UIImageView alloc] initWithFrame:CGRectMake(i*_scrollerview.frame.size.width, 0, _scrollerview.frame.size.width, _scrollerview.frame.size.height)];
                   imgview.contentMode=UIViewContentModeScaleAspectFill;
                    imgview.clipsToBounds=YES;
        UIImage *tempImg=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [imgview setImage:tempImg];
        [_scrollerview addSubview:imgview];
    }
    
    _scrollerview.contentSize = CGSizeMake((self.arrayOK.count) * (self.view.frame.size.width),0);
    [self.view addSubview:_scrollerview];
    
    
    //点击按钮，回到主发布页面
   /*
    //[_btnOK setBackgroundImage:[UIImage imageNamed:@"complete.png"] forState:UIControlStateNormal];
    [_btnOK setBackgroundColor:[UIColor orangeColor]];
    [_btnOK setTitle:[NSString stringWithFormat:@"完成(%lu)",(unsigned long)self.arrayOK.count] forState:UIControlStateNormal];
    _btnOK .titleLabel.font = [UIFont systemFontOfSize:10];
    [_btnOK addTarget:self action:@selector(complete:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnOK];
    */
    
}
-(void)complete:(UIButton *)sender{
    //NSLog(@"完成了,跳到主发布页面");
    //上传
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lu",(unsigned long)[self.arrayOK count]] forKey:@"uploadPic"];//逗号分隔，第一个是上传数量,后面是路径
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:HUD];
    // Set determinate bar mode
    HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
    HUD.delegate = self;
    // myProgressTask uses the HUD instance to update progress
    [HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
    
    
    
    /*
    for (int i=0; i<[self.arrayOK count]; i++) {
        ALAsset *asset=self.arrayOK[i];
        //CGImageRef ref = [[asset defaultRepresentation]fullScreenImage];
        CGImageRef ref = [[asset defaultRepresentation]fullResolutionImage];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref];
    
        [UIImageJPEGRepresentation(img, 1.0) writeToFile:self.imagepath atomically:YES];
        
        [self PostImage];
    }
    

    [self dismissViewControllerAnimated:YES completion:Nil];
    */
}
- (void)myProgressTask {
    // This just increases the progress indicator in a loop
    float progress = 0.0f;
    for (int i=0; i<[self.arrayOK count]; i++) {
        ALAsset *asset=self.arrayOK[i];
        //CGImageRef ref = [[asset defaultRepresentation]fullScreenImage];
        CGImageRef ref = [[asset defaultRepresentation]fullResolutionImage];
        UIImage *img = [[UIImage alloc]initWithCGImage:ref];
        
        [UIImageJPEGRepresentation(img, 1.0) writeToFile:self.imagepath atomically:YES];
        
        [self PostImage];
        while (progress < 1.0f) {
            progress += 0.01f;
            HUD.progress = progress;
            usleep(50000*(int)[self.arrayOK count]);
            if (progress*100<=100.0f) {
                HUD.labelText = [NSString stringWithFormat:@"%.f%%",progress*100];
            }
        }
    }
}
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    HUD = nil;
    [self dismissViewControllerAnimated:YES completion:Nil];
}

#pragma mark 上传图片
-(void)PostImage{
//    _engine=[[MKNetworkEngine alloc]initWithHostName:mainApi];
//    
//    MKNetworkOperation* op=[_engine operationWithPath:@"/upload/img.htm" params:nil httpMethod:@"POST"];
//    [op addFile:self.imagepath forKey:@"imgFile"];
//    
//    //[op setValue:@"imgFile" forKeyPath:@"name"];
//    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
//        //NSLog(@"%@",completedOperation.responseJSON);
//        NSDictionary* dict=completedOperation.responseJSON;
//        int error=[[dict objectForKey:@"error"]intValue];
//        
//        if (error==0) {
//            NSString* newImage=[dict objectForKey:@"saveDir"];
//            NSString *strPath=[[NSUserDefaults standardUserDefaults] objectForKey:@"uploadPic"];
//            strPath=[NSString stringWithFormat:@"%@;%@",strPath,newImage];
//            [[NSUserDefaults standardUserDefaults] setObject:strPath forKey:@"uploadPic"];
//            
//            //[self sendChatApi:@"image" withPath:newImage];
//        }
//    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
//        
//    }];
//    [_engine enqueueOperation:op];
}
-(void)OK:(UIButton *)sender{
    NSLog(@"点击了按钮，就取消选中这个图片");
    
}

-(void)dismiss{

    [self.navigationController popViewControllerAnimated:YES];
    /*
    if([[[UIDevice currentDevice]systemVersion] doubleValue]>=7.0){
        UIColor *red = [UIColor colorWithRed:255/255.0 green:48/255 blue:48/255 alpha:0.7];
        self.navigationController.navigationBar.barTintColor = red;
    }else{
        UIColor *red = [UIColor colorWithRed:255/255.0 green:48/255 blue:48/255 alpha:0.7];
        self.navigationController.navigationBar.TintColor = red;
    }
    */
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
